package com.njxxted.activiti.modules.process.task.handler;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.njxxted.activiti.common.annotation.StrategyHandleType;
import com.njxxted.activiti.common.constant.Constant;
import com.njxxted.activiti.common.util.WorkflowUtils;
import com.njxxted.activiti.modules.process.cmd.TaskHandleCmd;
import com.njxxted.activiti.modules.process.defintion.dao.ActRunDefinitionDao;
import com.njxxted.activiti.modules.process.defintion.entity.ActRunNodeConfigEntity;
import com.njxxted.activiti.modules.process.extend.entity.ExtendActInstanceEntity;
import com.njxxted.activiti.modules.process.extend.service.ExtendActInstanceService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.persistence.entity.TaskEntityImpl;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 描述：任务驳回到发起节点处理器（策略模式）
 * <p>
 * 作者：Ostrich Hu
 * 时间：2019/9/29 14:00 星期日
 */
@Component
@StrategyHandleType(Constant.Flow.TASK_BACK_2_START)
public class ActTaskBack2StartHandler extends AbstractTaskStrategyHandler {

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void taskHandle(TaskHandleCmd taskCmd) {
        Map<String, Object> elMap = taskCmd.getVariables();
        taskService.claim(taskCmd.getCurrNodeId(), taskCmd.getOperateUserId());
        WorkflowUtils.rollback(taskCmd.getCurrNodeId(), taskCmd.getComment(), true);
        List<HistoricTaskInstance> hisPreTask = WorkflowUtils.getHisPreActivity(taskCmd.getInstanceId());
        //定义一个list存放运行时的配置信息
        CopyOnWriteArrayList<ActRunNodeConfigEntity> assignUserList = new CopyOnWriteArrayList<>();
        //1.流程历史中驳回目标新创建的节点
        HistoricTaskInstance target = hisPreTask.get(hisPreTask.size() - 1);
        //2.流程历史中第一个节点
        HistoricTaskInstance firstTask = hisPreTask.get(0);
        //3.取出第一个节点的办理人
        ActRunNodeConfigEntity new_config = new ActRunNodeConfigEntity();
        new_config.setInstanceId(taskCmd.getInstanceId());
        new_config.setKey(taskCmd.getKey());
        new_config.setNodeId(target.getTaskDefinitionKey());
        new_config.setRunTaskId(target.getId());
        new_config.setConfigType(Constant.Flow.ASSIGN_USER);
        new_config.setConfigValue("/" + firstTask.getAssignee());
        new_config.setOtherValue("or");
        new_config.setAddDate(new Date());
        assignUserList.add(new_config);
        actRunDefinitionDao.insertBatch(assignUserList);
        //根据流程实例id查询流程实例信息
        ExtendActInstanceEntity instanceEntity = extActPInstanceService.queryObject(taskCmd.getInstanceId());
        User startedUser = identityService.createUserQuery().userId(instanceEntity.getStartUserId()).singleResult();
        //查询流程运行时的配置信息，用于推送消息
        Map<String, Object> conditionMap = Maps.newHashMap();
        conditionMap.put("instanceName", instanceEntity.getName());
        conditionMap.put("startedUser", startedUser.getLastName());
        conditionMap.put("currNodeName", taskCmd.getCurrNodeName());
        //推送消息
        pushNotice(taskCmd.getInstanceId(), taskCmd.getKey(), instanceEntity.getName(), target.getTaskDefinitionKey(), conditionMap);
        //设置驳回目标节点
        TaskEntityImpl nextTask = new TaskEntityImpl();
        nextTask.setId(target.getId());
        nextTask.setDueDate(target.getDueDate());
        nextTask.setName(target.getName());
        nextTask.setTaskDefinitionKey(target.getTaskDefinitionKey());
        setExtendActEntity(Constant.Flow.TASK_BACK_2_START, taskCmd, taskCmd.getCurrNodeId(), target.getId(), target.getName(), nextTask);
    }
}
